package kamikaze.service.product;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;
import kamikaze.support.UserSession.Type;

@ServiceConfig(path = "product/list", method = HttpMethod.GET)
public class ListProductService implements Service {

	@SuppressWarnings("unchecked")
	@Override
	public String serve(ServiceContext ctx) throws Exception {
		List<Product> productList = new ArrayList<Product>();
		boolean canEdit = true;

		Query q = null;
		if (ctx.getUserSession().getType() == Type.User) {
			q = ctx.getEntityManager()
					.createQuery(
							"Select p from Product p where deleted=false and ownerKey= :ownerKey");
			q.setParameter("ownerKey", ctx.getUserSession().asUser().getId());
		} else if (ctx.getUserSession().getType() == Type.Admin) {
			q = ctx.getEntityManager().createQuery(
					"Select p from Product p where deleted=false");
			canEdit = false;
		} else {
			throw new ServiceException("User not Login");
		}

		productList = q.getResultList();
		ctx.getRequest().setAttribute("canEdit", canEdit);
		ctx.getRequest().setAttribute("products", productList);

		return "product/list";

	}

}
